package com.hxkcloud.nurse.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hxkcloud.nurse.R;
import com.hxkcloud.nurse.adapter.HistoryRecordAdapter;
import com.hxkcloud.nurse.adapter.NewsListAdapter;
import com.hxkcloud.nurse.beans.ArticleBean;
import com.hxkcloud.nurse.beans.ArticleWholeBean;
import com.hxkcloud.nurse.request.MessageCode;
import com.hxkcloud.nurse.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.nurse.utils.SharedPreferenceUtil;
import com.hxkcloud.nurse.views.pulltorefreshlayout.PullToRefreshLayout;
import com.hxkcloud.nurse.views.pulltorefreshlayout.PullableRecyclerView;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by ray_lei on 2016/7/12.
 */
public class SearchNewsActivity extends BaseActivity implements View.OnClickListener, NewsListAdapter.ResultSelectedListener, PullToRefreshLayout.OnRefreshListener {

    private LinearLayout titleLayout;

    private EditText searchET;//搜索输入框
    private TextView cancelTV;//取消
    private TextView recordTV;//历史记录
    private ListView recordListView;//历史记录列表
    private HistoryRecordAdapter recordAdapter;

    private LinkedList<String> recordList;

    private PullToRefreshLayout refreshLayout;
    private PullableRecyclerView recycleView;
    private List<ArticleBean> newsInfoList;
    private NewsListAdapter adapter;

    private ArticleWholeBean resultBean;

    private String type = "";

    private int pageIndex = 1;
    private int pageSize = 15;

    private boolean isLoadMore = false;// 是否加载更多

    private boolean isChoose = false;

    private String keywords = "";

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_ARTICLELIST_SUCCESS:
                if (msg.obj != null) {
                    resultBean = (ArticleWholeBean) msg.obj;
                    if (resultBean.getList() != null) {

                        if (resultBean.getList().size() == 0) {
                            if (isLoadMore) {
                                refreshLayout
                                        .loadmoreFinish(PullToRefreshLayout.SUCCEED);
                            } else {
                                newsInfoList.clear();
                                adapter.setData(newsInfoList);
                                refreshLayout
                                        .refreshFinish(PullToRefreshLayout.SUCCEED);
                            }
                        } else {
                            if (isLoadMore) {

                            } else {
                                newsInfoList.clear();
                            }
                            newsInfoList.addAll(resultBean.getList());
                            adapter.setData(newsInfoList);
                            if (isLoadMore) {
                                refreshLayout
                                        .loadmoreFinish(PullToRefreshLayout.SUCCEED);
                            } else {
                                refreshLayout
                                        .refreshFinish(PullToRefreshLayout.SUCCEED);
                            }

                        }

                    } else {
                        newsInfoList.clear();
                        adapter.setData(newsInfoList);
                    }
                }

                break;
            case MessageCode.NETWORKCODE_ARTICLELIST_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                }

                break;

        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout_searchnews);
        newsInfoList = new ArrayList<ArticleBean>();
        recordList = new LinkedList<String>();
        if (SharedPreferenceUtil.getHistoryKeywords(mContext) != null) {
            String list = SharedPreferenceUtil.getHistoryKeywords(mContext);
            if (list != null && !"".equals(list)) {
                String list1 = list.substring(1, list.length() - 1);
                String[] arr = list1.split(",");
                System.out.println(arr[0]);
                int length = arr.length;
                if (length <= 10) {
                    for (int i = 0; i < length; i++) {
                        recordList.addFirst(arr[(length - 1) - i].trim());
                    }
                }

            }
        }
        if (this.getIntent().hasExtra("type")) {
            type = this.getIntent().getStringExtra("type");
        }
        isChoose = getIntent().getBooleanExtra("isChoose", false);
        initView();
        initData();
        initListener();
    }

    @Override
    protected void initView() {

        titleLayout = (LinearLayout) findViewById(R.id.searchnews_layout_title);
        setTitlePadding(titleLayout);

        searchET = (EditText) findViewById(R.id.searchnews_et_search);
        cancelTV = (TextView) findViewById(R.id.searchnews_tv_cancel);
        recordTV = (TextView) findViewById(R.id.searchnews_tv_history);
        recordListView = (ListView) findViewById(R.id.searchnews_lv_record);
        recordAdapter = new HistoryRecordAdapter(this, recordList);
        recordListView.setAdapter(recordAdapter);

        refreshLayout = (PullToRefreshLayout) findViewById(R.id.searchnews_refreshlayout);
        recycleView = (PullableRecyclerView) findViewById(R.id.searchnews_recyclerview);

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(mLayoutManager);
        refreshLayout.setOnRefreshListener(this);
        recycleView.setCanLoadMore(false);
        recycleView.setClickable(true);

        adapter = new NewsListAdapter(this, newsInfoList, recycleView, this, screenWidth,type);
        recycleView.setAdapter(adapter);

    }

    @Override
    protected void initListener() {
        cancelTV.setOnClickListener(this);

        searchET.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                // TODO Auto-generated method stub
                if (actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_ACTION_SEND || actionId == EditorInfo.IME_ACTION_SEARCH ||
                        (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)
                        || actionId == EditorInfo.IME_ACTION_DONE) {

                    keywords = searchET.getText().toString().trim();

                    if (keywords == null || "".equals(keywords)) {
                        // 提示为空
                    } else {
                        if (recordList.size() == 10) {
                            recordList.remove(recordList.size() - 1);
                        }
                        if (recordList.contains(keywords)) {
                            System.out.println("有=========");
                        } else {
                            recordList.addFirst(keywords);
                        }

                        SharedPreferenceUtil.setHistoryKeywords(mContext, recordList);
                        recordAdapter.notifyDataSetChanged();
                        recordTV.setVisibility(View.GONE);
                        recordListView.setVisibility(View.GONE);
                        refreshLayout.setVisibility(View.VISIBLE);
                        loading();
                        YiJiaHuNetWorkUtils.newarticleList(loginInfo.getDepartmentId(), keywords, "", type, pageIndex, pageSize, handler);
                    }
                    return false;
                }
                return false;
            }
        });

        recordListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                searchET.setText(recordList.get(position));
                recordTV.setVisibility(View.GONE);
                recordListView.setVisibility(View.GONE);
                refreshLayout.setVisibility(View.VISIBLE);
                YiJiaHuNetWorkUtils.newarticleList(loginInfo.getDepartmentId(), recordList.get(position), "", type, pageIndex, pageSize, handler);
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.searchnews_tv_cancel:
                finish();
                break;

        }
    }


    @Override
    public void onSelected(String type, ArticleBean info) {
        if (isChoose) {
            Intent iBack = new Intent();
            iBack.putExtra("id", info.getArticleId());
            iBack.putExtra("name", info.getName());
            setResult(RESULT_OK, iBack);
            finish();
        } else {
            Intent intent = new Intent(mContext, ArticleDetailActivity.class);
            intent.putExtra("articleId", info.getArticleId());
            intent.putExtra("name", info.getName());
            intent.putExtra("acctType", this.type);
            startActivity(intent);
        }
    }

    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        if (!TextUtils.isEmpty(keywords)) {
            loading();
            YiJiaHuNetWorkUtils.newarticleList(loginInfo.getDepartmentId(), keywords, "", type, pageIndex, pageSize, handler);
        } else {
            refreshLayout
                    .loadmoreFinish(PullToRefreshLayout.SUCCEED);
        }
    }

    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {

    }
}
